package com.stuManager.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import javax.sql.DataSource;
import javax.swing.plaf.nimbus.State;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class DBUtil {
    public static DataSource dataSource;
    //进行静态成员的初始化
    static {
        try {
            Properties p = new Properties();
            InputStream inputStream = DbUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            assert inputStream != null;
            p.load(inputStream);
            dataSource = DruidDataSourceFactory.createDataSource(p);
//            Class.forName(jdbcName);
            System.out.println("读取jdbc驱动");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        try {
            return dataSource.getConnection();
        }
        catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    //释放资源
    public static void closeConnection(Connection con, Statement statement) {
        if (null != con && statement != null) {
            try {
                statement.close();
                con.close();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection con, Statement statement, ResultSet resultSet) {
        if (con != null && statement != null && resultSet != null) {
            try {
                resultSet.close();
                statement.close();
                con.close();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
